package com.cheng.spider.constant;

import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ConstantMap {

    private static final Map<String, String> CONSTANT_MAP;

    static {
        CONSTANT_MAP = new HashMap<>();
        loadDefaultConfig();
        loadConfigFile(DefaultConstant.CLASSPATH + DefaultConstant.DEFAULT_CONFIG_FILENAME);
    }

    private ConstantMap(){}

    public static void put(String key, String value) {
        CONSTANT_MAP.put(key, value);
    }

    public static String get(String key) {
        return CONSTANT_MAP.get(key);
    }

    private static void loadDefaultConfig() {
        CONSTANT_MAP.put(ConstantName.CHARSET_NAME, DefaultConstant.DEFAULT_CHARSET_NAME);
    }

    private static void loadConfigFile(String fileName) {
        Properties properties = new Properties();
        try {
            properties.load(new FileReader(fileName));
            properties.forEach((k, v) -> {
                CONSTANT_MAP.put( (String)k, (String)v );
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
